<template>
    <div>
        <div class="right-wrapper-btnGroup">
            <div>
                <label>筛选区间：</label>
                <el-date-picker
                    v-model="baseData.startTime"
                    type="date"
                    placeholder="开始时间"
                    value-format="yyyy/MM/dd"
                    format="yyyy年MM月dd日"
                    size="small"
                    style="width:160px"
                    >
                </el-date-picker>
                    至
                <el-date-picker
                    v-model="baseData.endTime"
                    type="date"
                    value-format="yyyy/MM/dd"
                    format="yyyy年MM月dd日"
                    placeholder="结束时间"
                    size="small"
                    style="width:160px"
                    >
                </el-date-picker>
                <el-button  size="mini" type="primary" icon="el-icon-search" @keyup. style="margin-left:10px" @keyup.enter.native="getDateQueryList" @click="getDateQueryList">查询</el-button>
                <el-tooltip class="item" effect="dark" content="一键识别所有异常信息" placement="top-start">
                    <el-button  size="mini" type="danger" icon="el-icon-warning-outline" @keyup. style="margin-left:10px" @click="handleErrorData" v-if="showRoleCheck">异常识别</el-button>
                </el-tooltip>

                <el-tooltip class="item" effect="dark" content="无审核权限" placement="top-start">
                    <el-button  size="mini" type="danger" icon="el-icon-warning-outline" @keyup. style="margin-left:10px" @click="handleErrorData" v-if="!showRoleCheck" disabled>异常识别</el-button>
                </el-tooltip>
            </div>
            <div style="margin-top:4px">
                <el-dropdown @command="handleMoreClick">
                    <el-button type="primary" size="mini">
                        更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                       <el-dropdown-item icon="el-icon-download"  command="import" :disabled="showRoleAdd == 0"> 导入</el-dropdown-item>
                        <el-dropdown-item icon="el-icon-upload2" command="export"> 导出</el-dropdown-item>
                        <el-dropdown-item icon="el-icon-edit-outline"  command="filter"> 数据过滤</el-dropdown-item>
                        <el-dropdown-item icon="el-icon-document-copy" command="dataSet" :disabled="showRoleAdd == 0"> 数据录入</el-dropdown-item>
                        <el-dropdown-item icon="el-icon-link" command="concat" :disabled="showRoleEdit == 0"> 别名关联</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </div>
        <div class="collapse-content" style="margin-top: 10px;">
            <div class="collapse-card"  ref="table-wrapper">
                <div class="collapse-card-header" @click="toggleBox(1)">
                    <div class="collapse-title">
                        <div> <i class="iconfont title-icon">&#xe671;</i>数据展示</div>
                        <div class="describe">
                            <i class="iconfont greenText">&#xe711;</i> 正常
                            <i class="iconfont yellowText">&#xe711;</i> 异常
                            <i class="iconfont redText">&#xe711;</i> 错误
                        </div>
                    </div>
                
                    <div class="chart-actions">
                        <el-tooltip effect="dark" content="展开/折叠表格" placement="top">
                        <i 
                            class="el-icon-arrow-right expand-icon" 
                            :class="{ 'expanded': activeNames.includes(1) }"
                        ></i>
                        </el-tooltip>
                    </div>
                </div>
                <transition name="collapse">
                    <div class="right-wrapper-top" ref="table-wrapper" v-loading="tableLoading" element-loading-text="数据加载中，请稍后" element-loading-spinner="el-icon-loading" v-show="isTableExpanded">
                        <div class="table-tips" v-if="showRoleCheck">📝数据审核功能已启用。现支持通过右键点击数据表格中的单元格，唤出操作菜单，执行审核相关操作。</div>
                        <tableView :tableHeight="tableHeight" :tableList="tableList" :tableComPs="tableComPs" @preview="preview" v-if="tableList.length > 0" @updateValue="handleUpdateValue" @load-more="loadMoreData" :enable-virtual-scroll="enableVirtualScroll" :showRoleCheck="showRoleCheck"/>
                        <noData showData v-if="tableList.length == 0" />
                    </div>
                </transition>
            </div>
            <div class="collapse-card" style="margin-top:10px">
                <div class="collapse-card-header" @click="toggleBox(2)">
                    <div class="collapse-title">
                        <div> <i class="iconfont title-icon">&#xe7a8;</i>过程线展示</div>
                    </div>
                
                    <div class="chart-actions">
                        <el-tooltip effect="dark" content="展开/折叠图表" placement="top">
                        <i 
                            class="el-icon-arrow-right expand-icon" 
                            :class="{ 'expanded': activeNames.includes(2) }"
                        ></i>
                        </el-tooltip>
                    </div>
                </div>
                <transition name="collapse">
                    <div class="right-wrapper-bot" v-loading="chartLoading" element-loading-text="图形加载中，请稍后" element-loading-spinner="el-icon-loading" v-show="isChartExpanded">
                       <noData showChart v-if="chartData == null" />
                        <chartLine v-show="chartData != null" :chartData="chartData" :field="field" :watchTime="watchTime" height="220px" ref="chartRef"/>
                    </div>
                </transition>
            </div>
        </div>


        <!-- 弹窗部分 -->
        <ExcelTableDialog :visible.sync="ExcelTableDialog" :stationId="stationId" :treeID="treeID" :CodeId="CodeId" :instRID="instRID" @handleSaveDialogTable="getDateQueryList"/>
       
        <dataFilter :filterData="filtering" :visible.sync="filterDialog" @filteringSubmit="filteringSubmit"/>
        
        <exportExcel :visible.sync="exportExcelDialog" :stationId="stationId" />
        
        <importExcel :visible.sync="importExcelDialog" :stationId="stationId" @successImport="getDateQueryList"/>
        
        <AliasAssociation :visible.sync="AliasAssociationDialog" :stationId="stationId"/>
    </div> 
</template>
<script>
import {GetMonitoringList,GetValueAllEndCopy,updateValue,OutlierPoints} from "@/api/https";
import ExcelTableDialog from './ExcelTableDialog.vue'
import dataFilter from './dataFilter.vue'
import noData from '../../base/noData.vue'
import exportExcel from './ExportExcel.vue'
import importExcel from './importExcel.vue'
import AliasAssociation from './AliasAssociation.vue'
import TableView from './TableView.vue'
import chartLine from '@/components/base/chartLine.vue'
import DateUtils from '@/utils/dateUtils'
export default {
    props:{
        stationId:{
           type:[String,Number],
            default:''
        },
        treeID:{
            type:Number,
            default:0
        },
        CodeId:{
            type:Number,
            default:0
        },
        instRID:{
            type:Number,
            default:0
        },
        showRoleAdd:{
            type:Number,
            default:0
        },
        showRoleCheck:{
            type:Number,
            default:0
        },
        showRoleEdit:{
            type:Number,
            default:0
        }
    },
    components:{ExcelTableDialog,dataFilter,noData,exportExcel,importExcel,AliasAssociation,TableView,chartLine},
    data() {
        return {
            activeNames:[1,2],
            ExcelTableDialog:false,
            exportExcelDialog:false,
            importExcelDialog:false,
            filterDialog:false,
            tableLoading:false,
            chartLoading:false,
            AliasAssociationDialog:false,
            tableList:[],
            tableComPs:[],
            tableHeight:'calc(100vh - 600px)',
            myChart:null,
            baseData: {
                stationID: this.stationId,
                treeID: this.treeID,
                startTime: '',
                endTime: '',
                pageIndex: 1,
                pageSize: 30,
                timeSequence: '倒序',
            },
            filtering:{
                a: true,
                b: true,
                c: true,
                d: true,
                e: true,
                f: true,
                g: false,
                h: true,
                m: true,
                n: true,
                k:false,
                l:false,
                valueType: 6,
            },
            totalPage:1,
            compsLineValues:'',
            chartData:null,
            watchTime:null,
            field:null,
            enableVirtualScroll:false
        }
    },
    mounted(){
        this.baseData.startTime = DateUtils.formatDate(DateUtils.getDate('fiveyearsago'))
        this.baseData.endTime = DateUtils.formatDate(DateUtils.getDate('today'))
        this.getTableList();
    },
    deactivated(){
        this.enableVirtualScroll = false
        this.clearChart();
    },
    activated(){
        if(this.chartData){
            this.updateChart()
        }
        this.enableVirtualScroll = this.baseData.pageIndex < this.totalPage;
    },
    beforeDestroy() {
        this.$refs.chartRef?.cleanupChart();
        this.chartData = null;
        this.tableList = [];
        this.enableVirtualScroll = false
    },
    computed: {
        isTableExpanded() {
            return this.activeNames.includes(1);
        },
        isChartExpanded() {
            return this.activeNames.includes(2);
        }
    },
    watch:{
        'treeID':{
            handler(newVal,oldVal){
                if (newVal && newVal !== oldVal) {
                    this.watchTime = null
                    this.field = null
                    this.clearData()
                    this.baseData.treeID = newVal
                    this.getTableList();
                }
            },
            immediate: true
        },
        'stationId':{
            handler(newVal, oldVal) {
                if (newVal && newVal !== oldVal && oldVal != undefined) {
                    this.clearData();
                    this.getTableList();
                    this.baseData.treeID = newVal
                    this.watchTime = null
                    this.field = null
                }
            },
            immediate: true
        },
    },
    methods: {
        toggleBox(num) {
            const index = this.activeNames.indexOf(num);
            if (index > -1) {
                this.activeNames.splice(index, 1);
            } else {
                this.activeNames.push(num);
            }
            this.adjustTableHeight();
        },
        adjustTableHeight() {
            const hasTable = this.isTableExpanded;
            const hasChart = this.isChartExpanded;
            
             if (hasTable && !hasChart) {
                this.tableHeight = 'calc(100vh - 360px)';
            } else if (!hasTable && hasChart) {
                
            } else {
                this.tableHeight = 'calc(100vh - 600px)';
            }
        },
        clearData(){
            this.tableList = []
            this.tableComPs = []
            this.baseData.pageIndex = 1
            this.totalPage = 1
            this.clearChart();
            this.tableLoading = false
            this.chartLoading = false
            this.chartData = null
            this.compsLineValues = ''
        },
        getTableList() {
            if(this.CodeId){
                const { h, m, n } = this.filtering;
                let valueType = -1;

                if (h && !m && !n) valueType = 0;
                else if (!h && m && !n) valueType = 1;
                else if (!h && !m && n) valueType = 2;
                else if (h && m && !n) valueType = 3;
                else if (h && !m && n) valueType = 4;
                else if (!h && m && n) valueType = 5;
                else if (h && m && n) valueType = 6;

                this.filtering.valueType = valueType
                this.tableLoading = true
                const _data = {...this.baseData,...this.filtering}
                GetMonitoringList(_data).then(res=>{
                    if(res.isSuccess && res.data && res.data.node && res.data.node.length > 0){
                        this.filtering = res.data.filtering
                        this.totalPage = res.data.pagesNumber
                        this.tableComPs = res.data.comPs
                        //  后端数据给的格式不符合前端要求，因为需要前端写排序，所以重新组装一下格式
                        const _list = res.data.node.map(item => {
                            const { comPs_1, comPs, comP_outs, ...baseItem } = item
                            
                            const dynamicData = comPs_1.reduce((acc, key, index) => {
                                acc[key] = comPs[index]
                                acc[`${key}state`] = comP_outs[index]
                                return acc
                            }, {})
                            
                            return { ...baseItem, ...dynamicData }
                        })
                        // 数据部分
                        if(this.baseData.pageIndex > 1){
                            this.tableList = this.tableList.concat(_list);
                        }else{
                            this.tableList = [..._list]
                            const filterNumber = res.data.valueTypes.findIndex(item => {return item == 2})
                            if(filterNumber > -1){
                                this.compsLineValues = res.data.comPs[filterNumber]
                            }else{
                                this.compsLineValues = res.data.comPs[0]
                            }

                            if(this.tableList.length > 0){
                                this.getChartLineData()
                            }else{
                                this.chartLoading = false
                                this.chartData = null
                            }
                        }
                        this.tableLoading = false
                        
                        this.enableVirtualScroll = this.baseData.pageIndex < this.totalPage;
                    }else{
                        this.clearData()
                        this.clearChart()
                        this.chartData = null
                        this.$message.error(res.errorMessage)
                    }
                })
            }
        },
        // 过程线部分
        getChartLineData(){
             this.chartLoading = true
            GetValueAllEndCopy(this.CodeId,this.compsLineValues,this.filtering,this.baseData.startTime,this.baseData.endTime).then(res=>{
                if(res.isSuccess){
                    if (res.data && res.data.valueData != null) {
                      this.chartData = res.data
                      this.watchTime = null
                      this.field = null
                    }else{
                        this.chartData = null
                    }
                    this.chartLoading =false
                }else{
                    this.chartData = null
                    this.chartLoading = false
                    this.$message.error(res.errorMessage)
                }
            })
        },

        preview(row,column) {
            const excludeColumns = ['状态','编号','测点名称', '是否审核', '观测时间', '录入人员', '审核人员', '备注'];

            if (!excludeColumns.includes(column.title)) {
                  GetValueAllEndCopy(row.codE_ID,column.field,this.filtering,this.baseData.startTime,this.baseData.endTime).then(res =>{
                  if(res.isSuccess && res.data && res.data.valueData){
                    let lineData = res.data.valueData || [];
                    if (lineData.length > 0) {
                        this.chartLoading = true
                        this.chartData = res.data
                        const time = row.watchTime.split(' ')
                        this.watchTime = time[0]
                        this.field = row[column.field]
                        this.$nextTick(()=>{
                          this.updateChart();
                          this.chartLoading =false
                        })
                    }else{
                        this.chartData = null
                        this.chartLoading =false
                    }
                  }else{
                        this.chartData = null
                        this.chartLoading =false
                    }
              });
            }
        },

        getDateQueryList(){
            if (this.baseData.startTime && this.baseData.endTime) {
                const start = new Date(this.baseData.startTime)
                const end = new Date(this.baseData.endTime)
                
                if (end < start) {
                    this.$message.warning('结束时间不能小于开始时间！')
                    return
                }
            }
            this.clearData()
            this.getTableList();
        },
        
        handleErrorData(){
          if(this.treeLeftID == ''){
                this.$message.error('请选择左侧菜单')
                return false
            }else{
                OutlierPoints({
                    id:this.treeID
                }).then(res=>{
                    if(res.isSuccess){
                        this.$message.success('操作成功')
                        this.getDateQueryList()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }
        },
        handleUpdateValue(data){
            updateValue(data).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                        let err = []
                        let success = []
                        let message = ''
                        res.data.forEach(item=>{
                            if(item.rn){
                                success.push(item.id)
                            }else{
                                err.push(item.mess)
                                message += `<p style="line-height:30px">${item.mess}</p>`
                            }
                        })
                        if(err.length > 0){
                            this.$message({
                                type:'error',
                                dangerouslyUseHTMLString: true,
                                message: message
                            });
                        }
                        if(success.length > 0){
                            this.getDateQueryList()
                        }
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        },
        copyExcelClick(){
            if(this.CodeId){
                this.ExcelTableDialog = true
            }else{
                this.$message.error('此目录含有不止一类仪器不能录入数据，请选下级相应目录录入')
            }
        },
        filteringSubmit(filterData){
            this.filtering = {...filterData}
            this.getDateQueryList()
        },
        loadMoreData() {
            if (this.baseData.pageIndex < this.totalPage) {
                this.baseData.pageIndex++
                this.getTableList()
            }
        },
        clearChart() {
            if (this.$refs.chartRef) {
                this.$refs.chartRef.clearChart();
            }
        },
        updateChart() {
            if (this.$refs.chartRef) {
                this.$refs.chartRef.updateChart();
            }
        },
        handleMoreClick(command) {
            if(command == 'import'){
                this.importExcelDialog = true
            }else if(command == 'export'){
                this.exportExcelDialog = true
            }else if(command == 'filter'){
                this.filterDialog = true
            }else if(command == 'dataSet'){
                this.copyExcelClick()
            }else if(command == 'concat'){
                this.AliasAssociationDialog = true
            }
        }
    }
}
</script>
<style scoped lang="scss">
.right-wrapper-btnGroup{
    width: 100%;
    height: 60px;
    background: #fff;
    border-radius: 2px;
    padding:12px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}

::v-deep .ico{
    font-size: 20px !important;
    vertical-align: middle !important;
}
::v-deep .result{
    i{
        margin-right: 8px;
        font-size: 14px;
    }
}

.describe{
  font-weight: normal;
  margin-left:10px;
  font-size: 12px;
  i{
    font-size: 12px;
  }
}
</style>